/**
 * @Author:       lee
 * @Email:        liwei@hiynn.com
 * @DateTime:     2017-11-07 06:39:49
 * @Description:  迭代器
 */
/**
 *  使用ES5创建一个迭代器
 */
function createIterator(items) {
  var i = 0;
  return {
    next:function() {
      var done = (i >= items.length);
      var value = !done ? items[i++] : undefined;
      return {
        done:done,
        value:value
      }
    }
  }
}

var iterator = createIterator([1,2,3]);
console.log(iterator.next())
console.log(iterator.next())
console.log(iterator.next())

console.log(iterator.next())// {done: true, value: undefined}
console.log(iterator.next())// {done: true, value: undefined}
/**
 *  生成器
 *  yield只可在生成器内部使用
 */
function *createIterator() {
  yield 1;
  yield 2;
  yield 3;
}

let iterator = createIterator()
console.log(iterator.next().value)
/**
 *  生成器函数表达式
 *  由于生成器本身就是函数，因而可以将他们添加到对象中
 *  也可以使用ES6的函数方法
 */
let createIterator = function *(items) {
  for(let i = 0;i < items.length;i++) {
    yield items[i]
  }
}
let iterator = createIterator([11,22,33])
console.log(iterator.next())
console.log(iterator.next())
console.log(iterator.next())
console.log(iterator.next())
//------------------------------------------------------------
/**
 *  for-of循环
 */
let values = [1,2,3];
for(let num of values) {
  console.log(num)
}
//访问默认迭代器
let values = [1,2,3];
let iterator = values[Symbol.iterator]()
console.log(iterator.next())
console.log(iterator.next())
console.log(iterator.next())
console.log(iterator.next())
//------------------------------------------------------------
/**
 *  创建可迭代对象
 */
let collection = {
  items:[],
  *[Symbol.iterator]() {
    for(let item of this.items) {
      yield item;
    }
  }
}
collection.items.push(1)
collection.items.push(2)
collection.items.push(3)
collection.items.push(4)

for(let x of collection) {
  console.log(x)
}
//------------------------------------------------------------
/**
 *  内建迭代器
 */
































